/**
 * Created by Administrator on 2017/3/21.
 */
import React, { Component, Fragment } from 'react';
import { Form, Input, DatePicker, message, Button, Tabs, Alert, Table,Col,Icon } from 'antd';
import { connect } from 'dva';
import L from 'leaflet';   //引入leaflet
import MyPagination from '@/components/MyPagination';
import './index.less';
import './../Home/leaflet.less';
import Template2 from './Template2';
import { getTimeDistance,timeStamp } from '@/utils/utils';
import ReactDataGrid from 'react-data-grid';
import forEach from 'lodash/forEach';
import moment from 'moment';
import request from '@/utils/request';
import ReactEcharts from 'echarts-for-react';
import Loading from "@/components/Loading";
const { TabPane } = Tabs;
const ButtonGroup = Button.Group;

class AddPoliciesForm extends Component {
  constructor(props) {
    super(props);

    this.state = {
      loading:false,
      date: moment().format('YYYY-MM-DD'),
      data0:[],
      data1:[],
      data2:[],
      data3:[],
    };
  }

  componentDidMount() {
    const that = this;
    if(Array.isArray(this.props.channel)){
      console.log("获取数组")
      for(let i=0;i<this.props.channel.length;i++){
        this.fetchData({
          type:this.props.type,
          channel:this.props.channel[i],
        })
      }
    }else{
      this.fetchData({
        type:this.props.type,
        channel:this.props.channel,
      })
    }

  }

  fetchData = (params) => {
    const that = this;
    this.setState({
      loading: true,
    });
    request(`/all_workstation_historical_data`, {
      method: 'GET',
      params: {
        ...params,
        start_date: this.state.date,
        end_date: this.state.date,
        workstation_id: this.props.workstation_id,
        order_direction:'desc'
      },
    }).then(response => {
      if (response.status === 200) {
        that.setState({
          [`data${params.channel}`]:response.data.data,
          loading: false,
        });
      }
    });
  };
  handleRangePickerChange = (dateString) => {
    console.log('dateString',dateString)
    this.setState({
      date: dateString,
    }, function() {
      if(Array.isArray(this.props.channel)){
        console.log("获取数组")
        for(let i=0;i<this.props.channel.length;i++){
          this.fetchData({
            type:this.props.type,
            channel:this.props.channel[i],
          })
        }
      }else{
        this.fetchData({
          type:this.props.type,
          channel:this.props.channel,
        })
      }
    });
  };
  getOption=()=>{
    let time=[];
    let data=[];
    let renderName=Array.isArray(this.props.renderName)?this.props.renderName:[this.props.renderName]
    let name=Array.isArray(this.props.name)?this.props.name:[this.props.name]
    let color=Array.isArray(this.props.color)?this.props.color:[this.props.color]
    for(let i=0;i<renderName.length;i++){
      window[renderName[i]]=[]
    }
    let data_0=JSON.parse(JSON.stringify(this.state[`data${this.props.channel}`]))
    let data_0_reverse=data_0.reverse()
    let series=[];
    console.log('renderName',renderName)
    console.log('data_0_reverse',data_0_reverse)
    for(let i=0;i<renderName.length;i++){
      for(let j=0;j<data_0_reverse.length;j++){
        if(data_0_reverse[j]){
          if(i==0){
            time.push(data_0_reverse[j].collected_at.slice(11))
          }
          if(this.props.remark&&this.props.name==='液位'){
            window[renderName[i]].push((data_0_reverse[j].data[renderName[i]]+this.props.remark).toFixed(3));
          }else{
            window[renderName[i]].push(data_0_reverse[j].data[renderName[i]]);
          }

        }
      }

      series.push( {
        name: name[i],
        type: 'line',
        smooth:true,
        symbol: 'none',
        data:  window[renderName[i]],
        large: true,
        lineStyle:{
          width:renderName.length>2?2:5
        },
      },)
    }
    console.log('series',series)
    let option = {
      color:color,
      title: {
        show:false,
        text: '',
        left:'10',
        top:'20',
        textStyle:{
          color:'#ffda00'
        }
      },


      toolbox: {
        show: true,
        iconStyle:{
          color:'#fff',
          borderColor:'#fff'
        },
        emphasis: {
          iconStyle: {
            color: "rgb(255,255,255)"
          }
        },
        feature: {
          dataView: { show: true, readOnly: false },
          magicType: { show: true, type: ['line', 'bar'] },
          restore: { show: true },
          saveAsImage: { show: true }
        }
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data:name,
        top:'20',
      },
      dataZoom: [
        {
          type: 'inside'
        }
      ],
      grid: {
        top:'10%',
        left: '3%',
        right: '5%',
        bottom: '4%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data:time,
        axisLabel: {
          showMaxLabel: true
        }
      },
      yAxis: [
        {
          type: 'value',
          name:'值',
        },
      ],
      series:series
    };
    return option
  }
  getArrOption=()=>{
    let time=[];
    window.data0=[];
    window.data_0=JSON.parse(JSON.stringify(this.state.data0))
    window.data_0_reverse=window.data_0.reverse()
    window.data1=[];
    window.data_1=JSON.parse(JSON.stringify(this.state.data1))
    window.data_1_reverse=window.data_1.reverse()
    window.data2=[];
    window.data_2=JSON.parse(JSON.stringify(this.state.data2))
    window.data_2_reverse=window.data_2.reverse()
    window.data3=[];
    window.data_3=JSON.parse(JSON.stringify(this.state.data3))
    window.data_3_reverse=window.data_3.reverse()
    let series=[]
    const that=this
    for(let i=0;i<this.props.channel.length;i++){
      window[`data${i}`] =window[`data_${i}_reverse`].map((item, index) => {
        return [(moment(item.collected_at, "YYYY-MM-DD  HH:mm:ss").diff(moment(that.state.date, "YYYY-MM-DD  HH:mm:ss"))) / 1000, item.data[that.props.renderName]]
      });
      series.push( {
        name: this.props.name[i],
        type: 'line',
        smooth:true,
        symbol: 'none',
        data: window[`data${i}`],
        large: true,
        lineStyle:{
          width:2
        },
      },)
    }
    let option = {
      color:this.props.color,
      title: {
        show:false,
        text: '',
        left:'10',
        top:'20',
        textStyle:{
          color:'#ffda00'
        }
      },
      toolbox: {
        show: true,
        iconStyle:{
          color:'#fff',
          borderColor:'#fff'
        },
        emphasis: {
          iconStyle: {
            color: "rgb(255,255,255)"
          }
        },
        feature: {
          dataView: { show: true, readOnly: false },
          magicType: { show: true, type: ['line', 'bar'] },
          restore: { show: true },
          saveAsImage: { show: true }
        }
      },
      // tooltip: {
      //   trigger: 'axis'
      // },
      tooltip: {
        trigger: 'axis',
        formatter: function (datas) {
          var res = ''
          for (var i = 0, length = datas.length; i < length; i++) {
            // console.log('datas[i]',datas[i])
            let time = (moment(that.state.date).add(datas[i].data[0], 's')).format('MM-DD HH:mm:ss')
            // let time=''
            let value = datas[i].data[1]
            res += time + '：' + datas[i].seriesName + '：'
              + value + '<br/>'
          }
          return res
        }
      },
      legend: {
        data:this.props.name,
        top:'20',
      },
      dataZoom: [
        {
          type: 'inside'
        }
      ],
      grid: {
        top:'10%',
        left: '3%',
        right: '5%',
        bottom: '4%',
        containLabel: true
      },
      xAxis: {
        type: 'value',
        boundaryGap: false,
        // data:time,
        axisLabel: {
          showMaxLabel: true,
          formatter: function (value, index) {
            return (moment(that.state.date).add(value, 's')).format('HH:mm:ss')
          }
        }
      },
      yAxis: [
        {
          type: 'value',
          name: '压力',
        },
      ],
      series: series
    };
    return option
  }

  render() {
    console.log('render')
    let template = '';
    const that = this;
    return (
      <div style={{ position:'relative'}}>
        <div style={{marginBottom:'10px'}}>
          <DatePicker
            value={moment(this.state.date)}
            allowClear={false}
            format="YYYY-MM-DD"
            style={{ width: 150, marginRight: '10px' }}
            placeholder={'选择日期'}
            onChange={(e, dateString) => this.handleRangePickerChange(dateString)}
          />
          <Button.Group >
            <Button type="primary" onClick={()=>{
              this.handleRangePickerChange(moment(this.state.date).add(-1,'days').format('YYYY-MM-DD'))
            }}>
              <Icon type="left" />
              前一日
            </Button>
            <Button type="primary" onClick={()=>{
              this.handleRangePickerChange(moment(this.state.date).add(1,'days').format('YYYY-MM-DD'))
            }}>
              后一日
              <Icon type="right" />
            </Button>
          </Button.Group>
        </div>
        {
          Array.isArray(this.props.channel)?
            <ReactEcharts
              option={this.getArrOption()}
              style={{ height: '500px', width: '100%' }}
              theme='my_theme'
            />:
            <ReactEcharts
              option={this.getOption()}
              style={{ height: '500px', width: '100%' }}
              theme='my_theme'
            />
        }

        {
          this.state.loading && <Loading/>
        }
      </div>

    );
  }
}

const AddPoliciesFormWrap = Form.create()(AddPoliciesForm);
export default connect()(AddPoliciesFormWrap);
